package net.htjs.juc.chapter06.longadder;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.Consumer;
import java.util.function.Supplier;

@Slf4j
public class NormalAdder {

    public static void main(String[] args) throws InterruptedException {
        for(int i = 0; i < 10; i++) {
            demo(()-> new AtomicLong(0), (atomicLong) -> atomicLong.incrementAndGet());

        }
        for(int i = 0; i < 10; i++) {
            demo(() -> new LongAdder(), (adder) -> adder.increment());
        }
    }

    /**
     * supplier ()->结果 提供累加器对象
     * (参数) -> 执行累加操作
     * @param adderSupplier
     * @param action
     * @param <T>
     */
    private static <T> void demo(Supplier<T> adderSupplier, Consumer<T> action) {
        T adder = adderSupplier.get();
        List<Thread> threads = new ArrayList<>();
        //4个线程，每人累加50万
        for(int i = 0; i < 4; i++) {
            threads.add(new Thread(() -> {
                for(int j = 0; j < 500000; j++) {
                    action.accept(adder);
                }
            }));
        }

        threads.forEach(Thread::start);
        long start = System.currentTimeMillis();
        threads.forEach(thread -> {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        long end = System.currentTimeMillis();
        log.info("adder:{}, cost:{}", adder,(end - start));

    }
}
